<template>
  <div class="main">
    <div class="container">
      <div class="banner">
        <div class="banner-content">
          <div class="banner-title">
            <img src="@/assets/images/home_new/banner-title.png" />
          </div>
          <div class="search-content" :sytle="{ marginTop: `${userLanguage.code == 'zh_CN' ? '197px' : '113px'}` }">
            <div class="search-container">
              <div class="search-input">
                <div class="cursor-pointer"><img class="w-6 h-6" src="@/assets/images/icons/icon_search.png"></div>
                <div class="input-wrap">
                  <div v-if="search == ''" class="search-type">
                    <div class="text ff-regular">{{ $t('home.placeholder') }}</div>
                    <img class="image" src="@/assets/images/home/search_type.png" alt="" />
                  </div>
                  <Input clearable class="input" @on-keyup="keySearch" v-model="search" type="text"> </Input>
                </div>
                <div class="camera-icon">
                  <Upload :show-upload-list="false" :headers="{
                    'X-Access-Token': userToken,
                    lang: 'en_US',
                  }" name="imageBase64" :before-upload="handleBeforeUpload" :on-progress="onProgress"
                    :on-success="onSuccess" :on-error="onError" :action="uploadURL">
                    <div class="loading-wrap" v-if="uploadLoading">
                      <t-loading></t-loading>
                    </div>
                    <img v-if="imgUrl" class="upload-image" :src="imgUrl" alt="" />
                    <img v-else src="@/assets/images/icons/icon_search_default.png" alt="" />
                  </Upload>
                </div>
                <div class="search-btn ff-regular" @click="onSearch">
                  {{ $t('home.search_test') }}
                </div>
              </div>

              <div class="tag">
                <!-- 好物推荐 -->
                <!-- <img src="@/assets/images/user/pc_toppicks.png" @click="jumpMet()" class="shop-btn" alt=""> -->
                <!-- 春节不打烊 -->
                <div class="spring-festival" @click="jumpSpring"
                  v-if="config.firstPageSwitchMap && config.firstPageSwitchMap.first_page_switch_chunjie && config.firstPageSwitchMap.first_page_switch_chunjie == 'ENABLE'">
                  <img src="@/assets/images/icons/icon_box.png" class="parcel-icon" alt="">
                  <div class="spring-text">{{ $t('estimation.newYearOpen') }}</div>
                </div>

                <div class="spring-festival" @click="jumpSpring">
                  <img src="@/assets/images/icons/icon_box.png" class="parcel-icon" alt="">
                  <div class="spring-text">{{ $t('estimation.newYearOpen') }}</div>
                </div>

                <a class="tag-item ff-regular seab" title="DIY" href="/search/DIY">DIY</a>
                <a class="tag-item ff-regular seab" :title="tipText" :href="`/search/${tipText}`">{{ tipText }}</a>
              </div>
            </div>
          </div>

          <div class="flow">
            <div class="flow-item">
              <img src="@/assets/images/home_new/banner_guide-1.png" class="img">
              <div class="info">
                <div class="title">Safe Purchase</div>
                <div class="text"> Refund for any issues </div>
              </div>
            </div>
            <div class="flow-arrow"><img class="w-6 h-6" src="@/assets/images/home_new/banner_arrow.png"></div>
            <div class="flow-item"><img src="@/assets/images/home_new/banner_guide-2.png" class="img">
              <div class="info">
                <div class="title">QC &amp; Storage</div>
                <div class="text"> Refund for any issues </div>
              </div>
            </div>
            <div class="flow-arrow"><img class="w-6 h-6" src="@/assets/images/home_new/banner_arrow.png"></div>
            <div class="flow-item"><img src="@/assets/images/home_new/banner_guide-3.png" class="img">
              <div class="info">
                <div class="title">Ship Guarantee</div>
                <div class="text"> Ship Guarantee </div>
              </div>
            </div>
          </div>

          <div class="banner-imgs">
            <span class="img1"><img src="@/assets/images/icons/banner_img_1.png" alt=""></span>
            <span class="img2"><img src="@/assets/images/icons/banner_img_2.png" alt=""></span>
            <span class="img3"><img src="@/assets/images/icons/banner_img_3.png" alt=""></span>
            <span class="img4">
              <div class="product-item">
                <div class="img">
                  <img :src="products[0].image" :alt="products[0].name">
                </div>
                <div class="product-info">
                  <p class="product-name">
                    <t-platform class="type" :type="products[0].channel"></t-platform>
                    <span class="name">{{ products[0].name }}</span>
                  </p>
                  <p class="product-stock" v-if="products[0].stock">{{ products[0].stock }}</p>
                  <p class="product-price">
                    $ {{ products[0].price }}
                    <span class="compare-price">
                      <span class="vs">VS</span>
                      <span class="price-text">
                        <span class="icon">
                          <img src="@/assets/images/icons/logo_amazon.png" alt="">
                        </span>
                        {{ products[0].comparePrice || 100 }}
                      </span>
                    </span>
                  </p>
                </div>
              </div>
            </span>
            <span class="img5">
              <div class="product-item">
                <div class="img">
                  <img :src="products[1].image" :alt="products[1].name">
                </div>
                <div class="product-info">
                  <p class="product-name">
                    <t-platform class="type" :type="products[1].channel"></t-platform>
                    <span class="name">{{ products[1].name }}</span>
                  </p>
                  <p class="product-stock" v-if="products[1].stock">{{ products[1].stock }}</p>
                  <p class="product-price">
                    $ {{ products[1].price }}
                    <span class="compare-price">
                      <span class="vs">VS</span>
                      <span class="price-text">
                        <span class="icon">
                          <img src="@/assets/images/icons/logo_amazon.png" alt="">
                        </span>
                        {{ products[1].comparePrice || 100 }}
                      </span>
                    </span>
                  </p>
                </div>
              </div>
            </span>
          </div>
        </div>
      </div>
      <img v-if="false" src="@/assets/images/home/strip_img1.png" class="strip-img" alt="">
      <div class="notice-bar">
        <div class="notice-content">
          <span class="icon">
            <img src="@/assets/images/icons/icon_notice.png" alt="">
          </span>
          <div class="scroll-container">
            <div class="announcement-item" v-for="(item, index) in logisticsList" :key="index">
              <template>
                <div class="title ff-regular" @click="onNoticeDetails(item.id)">
                  <span class="text">{{ item.title }}</span>
                  <span class="link">Click & Buy Now! <img src="@/assets/images/icons/icon_arrow_right.png" /></span>
                </div>
                <!-- <div class="date ff-regular">{{ item.createTime }}</div> -->
              </template>
            </div>
          </div>
        </div>
      </div>

      <!--活动轮播图-->
      <div class="custom100">
        <div class="carlos" v-if="slides">
          <div class="huandeng helpMeFind">
            <span class="huandeng-title"># Help Me Find</span>
            <div class="caca helpMeFind">
              <div id="helpMeFind" class="swiper-container">
                <div class="swiper-wrapper">
                  <div v-for="(item, index) in slides['helpMeFind']" :key="index" class="swiper-slide">
                    <div class="carlos-item" :class="index == 0 ? 'layout-1' : 'layout-2'">
                      <span class="avatar"></span>
                      <div class="info">
                        <div class="app-name">100Buy</div>
                        <div class="shop-name">
                          <t-platform class="type" :type="'TAOBAO'"></t-platform>
                          <span class="text">Aj11 Kang buckle big devil basketball</span>
                        </div>
                        <div class="goods-list">
                          <div class="goods-item">
                            <span class="img">
                              <img :src="item.images[0]" alt="">
                            </span>
                            <span class="btn">USD 4.14</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="huandeng">
            <span class="huandeng-title"># Ask QC</span>
            <div class="caca askQc">
              <div id="askQc" class="swiper-container">
                <div class="swiper-wrapper">
                  <div v-for="(item, index) in slides['askQc']" :key="index" class="swiper-slide">
                    <div class="carlos-item" :class="index <= 4 ? ('layout-' + (index + 1)) : 'layout-1'">
                      <span class="avatar"></span>
                      <div class="info">
                        <div class="app-name">100Buy</div>
                        <div class="shop-name">
                          <span class="text">QC Photos for details</span>
                        </div>
                        <div class="goods-list">
                          <div class="goods-item" v-for="(v, i) in [1, 2, 3, 4]" :key="i">
                            <span class="img">
                              <img :src="item.images[0]" alt="">
                            </span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="huandeng">
            <span class="huandeng-title"># Haul Share</span>
            <div class="caca haulShare">
              <div id="haulShare" class="swiper-container">
                <div class="swiper-wrapper">
                  <div v-for="(item, index) in slides['haulShare']" :key="index" class="swiper-slide">
                    <div class="carlos-share-item">
                      <div class="user">
                        <span class="name">Slein978</span>
                        <span class="text">in</span>
                        <span class="img"><img src="@/assets/images/icons/icon_1.png" /></span>
                        <span class="text">· 1h ago</span>
                      </div>
                      <div class="title">Big Haul</div>
                      <div class="goods-list">
                        <div class="goods-item">
                          <span class="img">
                            <img :src="item.images[0]" alt="">
                          </span>
                        </div>
                        <div class="goods-item">
                          <span class="img">
                            <img :src="item.images[0]" alt="">
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="joinDiscord">
          <span>Join</span>
          <img src="@/assets/images/home_new/join_discord.png" width="121" />
        </div>
      </div>

      <div class="service-target ff-bold">{{ $t('home.Onestopservice') }}</div>
      <div class="product-container">
        <ul class="product-list">
          <li v-for="(product, index) in products" :key="index" class="product-item">
            <!-- <div class="product-tag" v-if="product.tag">{{ product.tag }}</div> -->
            <div class="img">
              <img :src="product.image" :alt="product.name">
            </div>
            <div class="product-info">
              <p class="product-name">
                <t-platform class="type" :type="product.channel"></t-platform>
                <span class="name">{{ product.name }}</span>
              </p>
              <p class="product-stock" v-if="product.stock">{{ product.stock }}</p>
              <p class="product-price">
                $ {{ product.price }}
                <span class="compare-price">
                  <span class="vs">VS</span>
                  <span class="price-text">
                    <span class="icon">
                      <img src="@/assets/images/icons/logo_amazon.png" alt="">
                    </span>
                    {{ product.comparePrice || 100 }}
                  </span>
                </span>
              </p>
            </div>
          </li>
        </ul>

        <div class="more">
          <Button>Load More</Button>
        </div>
      </div>

      <!-- 公告弹窗- -->
      <announcement-popup></announcement-popup>
    </div>
  </div>
</template>

<script>
import Swiper from "swiper";
import "swiper/css/swiper.css";
import HomeTitle from "@/views/main/home/components/home-title";
import Product from "@/views/main/home/components/product";
import { hotSaleProductList, productImageUpload, productUpload } from "@/api/product";
import { mapState } from "vuex";
import TLoading from "@/components/t-loading";
import { getCoupon, homeCouponList, resolveAddress } from "@/api/order";
import AnnouncementPopup from "@/views/main/home/components/announcement-popup";
import TNoData from "@/components/t-no-data";
import service_buy from "@/assets/images/home/service_buy.png"
import service_warehouse from "@/assets/images/home/service_warehouse.png"
import service_check from "@/assets/images/home/service_check.png"
import service_transport from "@/assets/images/home/service_transport.png"
import { searchByUrl, searchSepUrl } from '@/common/search-helper'
import { toSeoFriendsChannel, isJumpWeb } from "@/common/common";
import { toHomePage, leaveHomePage, homeSeatchText } from "@/common/point/taobao";//淘宝埋点
import { pointUser } from "@/common/point/api-hook";//打点日志
import RigGoodsPop from './components/rig-goods-pop.vue';
import Recommend from './mock/recommend'
import Products from './mock/list'
import TPlatform from "@/components/t-platform";

export default {
  name: "Home-index",
  components: { AnnouncementPopup, TLoading, Product, HomeTitle, TNoData, RigGoodsPop, TPlatform },
  data() {
    return {
      products: Products,
      slides: null,
      servicesList: [{
        icon: service_buy,
        title: this.$t('home.Placeanorder'),
        text: this.$t('home.Placeanordertext')
      }, {
        icon: service_warehouse,
        title: this.$t('home.Deliverytoourwarehouse'),
        text: this.$t('home.Deliverytoourwarehousetext')
      }, {
        icon: service_check,
        title: this.$t('home.Qualityassurance'),
        text: this.$t('home.Qualityassurancetext')
      }, {
        icon: service_transport,
        title: this.$t('home.Globalshippingbecomeseasy'),
        text: this.$t('home.Globalshippingbecomeseasytext')
      }],
      form: {
        pageNo: 1,
        pageSize: 20,
      },
      appName: process.env.VUE_APP_NAME,
      loading: false,
      noMore: false,
      uploadURL: productImageUpload(),
      userToken: localStorage.getItem("USER_TOKEN"),
      imgUrl: "",
      id: "",
      search: "",
      value: "",
      currentSwiper: "",
      searchValue: "商品",
      dataInfo: "",
      uploadLoading: false,
      banner: [],
      hotList: [], // 热门商品
      tipText: this.$t('home.tip_test'),
      loadSuccess: false
    };
  },

  created() {
    toHomePage();
  },
  computed: {
    ...mapState({
      config: (state) => state.config.config,
      userInfo: (state) => state.user.userInfo,
      firstPageSwitchMap: (state) => {
        // 类目是否显示
        let obj = {};
        if (state.config.config) {
          obj = state.config.config.firstPageSwitchMap;
        }
        return obj;
      },
      logisticsList: (state) => {
        // 物流公告
        let list = [];
        if (state.config.config) {
          list = state.config.config.groupArticleListMap.CFG_GROUP_LOGISTICS;
        }
        return list;
      },
      activityList: (state) => {
        // 活动公告
        let list = [];
        if (state.config.config) {
          list = state.config.config.groupArticleListMap.CFG_GROUP_ACTIVITY;
        }
        return list;
      },
      othersList: (state) => {
        // 其他公告
        let list = [];
        if (state.config.config) {
          list = state.config.config.groupArticleListMap.CFG_GROUP_OTHERS;
        }
        return list;
      },
      guideBeginner: (state) => {
        // 新手指引
        let obj = "";
        if (state.config.config) {
          obj = state.config.config.articleMap.CFG_ARTICLE_BEGINNER_GUIDE;
        }
        return obj;
      },
      userLanguage: (state) => state.user.userLanguage,
      userCurrency: (state) => state.user.userCurrency,
    }),
    bannerCom() {

      //   openUrl(item) {
      //   if (item.jump.includes('drainagesDrainage')) {
      //     this.$router.push('/download');
      //   } else if (item.linkType === 'INTERNAL') {
      //     this.$router.push(item.jump)
      //   } else {
      //     window.open(item.jump);
      //   }
      // }

      return [{
        id: 1,
        titie: 1,
        linkType: 'INTERNAL',
        jump: '/register',
        image: 'https://img.allchinabuy.com/images/daigou-admin/2024/09/29/aca75e5f-9bd9-423a-a487-568d631aae33.jpg'
      }, {
        id: 2,
        titie: 2,
        linkType: 'out',
        jump: 'https://100buy.com/en_US/help_center?id=39',
        image: 'https://img.allchinabuy.com/images/daigou-admin/2024/03/25/e4256560-1de8-4200-8f6b-4022e8d6a09a.png'
      }, {
        id: 3,
        titie: 3,
        linkType: 'out',
        jump: 'https://discord.gg/H5fEeBCY3y',
        image: 'https://img.allchinabuy.com/images/daigou-admin/2024/03/25/938e8b86-ad54-40e0-93f5-c80c544c2004.png'
      }]
      // return this.banner.filter(item => item.jump != 'christmas');
    }
  },
  watch: {
    config() {
      if (this.config) {
        this.getBannerList();
      }
    },
    firstPageSwitchMap() {
      if (this.firstPageSwitchMap) {
        if (this.firstPageSwitchMap.first_page_switch_hot_spu == "ENABLE") this.getHotFocusProductList();
      }
    }
  },
  mounted() {
    pointUser('actions', '2000');
    if (this.config) {
      this.getBannerList();
    }
    this.initSlides()
    // if (this.firstPageSwitchMap.first_page_switch_hot_spu == "ENABLE") this.getHotFocusProductList();
    this.loadSuccess = false;
    setTimeout(() => {
      this.loadSuccess = true;
    }, 500);
  },
  methods: {
    //春节不打烊
    jumpSpring() {
      if (this.config.firstPageSwitchMap && this.config.firstPageSwitchMap.first_page_switch_chunjie && this.config.firstPageSwitchMap.first_page_switch_chunjie == 'ENABLE') {
        let kDoc = this.config.firstPageSwitchMap && this.config.firstPageSwitchMap.first_page_switch_chunjie_doc ? this.config.firstPageSwitchMap.first_page_switch_chunjie_doc : '';
        let text = kDoc.indexOf('keyword=') != -1 ? kDoc.split('keyword=')[1] || 'hiphop' : 'hiphop';
        pointUser('actions', '3004');
        this.$router.push(`/spring?text=${text}`)
      }
    },
    jumpMet() {
      pointUser('actions', '3003-3');
      this.$router.push('/shopWindow')
    },

    initSlides() {
      // if (process.env.NODE_ENV !== 'development')
      //   return

      this.slides = Recommend;

      this.$nextTick(() => {
        // 初始化swiper
        new Swiper('#helpMeFind', {
          direction: 'vertical',
          height: 260,
          slidesPerView: 1,
          loop: true,             // 循环模式
          autoplay: {
            delay: 3000,          // 自动切换间隔（ms）
            disableOnInteraction: false // 用户操作后不停止
          },
        });
        this.askQcSwiper = new Swiper('#askQc', {
          direction: 'vertical',
          height: 260,
          slidesPerView: 1,
          loop: true,             // 循环模式
          // autoplay: {
          //   delay: 3500,          // 自动切换间隔（ms）
          //   disableOnInteraction: false // 用户操作后不停止
          // },
        });
        this.haulShareSwiper = new Swiper('#haulShare', {
          direction: 'vertical',
          height: 260,
          slidesPerView: 1,
          loop: true,             // 循环模式
          autoplay: {
            delay: 3300,          // 自动切换间隔（ms）
            disableOnInteraction: false // 用户操作后不停止
          },
        });
      })

    },

    getBannerList() {
      this.banner = this.config.bannerGroup.MIDDLE;
      // this.initSwiper();
    },
    // 初始化swiper
    initSwiper() {
      this.$nextTick(function () {
        this.currentSwiper = new Swiper(".mySwiper", {
          slidesPerView: 3,
          spaceBetween: 0,
          // navigation: {
          //   nextEl: ".swiper-button-next",
          //   prevEl: ".swiper-button-prev",
          // },
          // pagination: {
          //   el: ".swiper-pagination",
          //   clickable: true,
          // },
        });
      });
    },
    onNoticeDetails(id) {
      // 公告详情
      this.$router.push(`/notice/${id}`);
    },
    openUrl(item) {
      if (item.jump.includes('drainagesDrainage')) {
        this.$router.push('/download');
      } else if (item.linkType === 'INTERNAL') {
        this.$router.push(item.jump)
      } else {
        window.open(item.jump);
      }
    },
    getHotFocusProductList() {
      if (this.noMore) {
        return false;
      }
      if (this.loading) {
        return false;
      }
      this.loading = true;
      // 热销商品列表
      hotSaleProductList(this.form)
        .then((res) => {
          let data = res.result.records;
          for (let i = 0; i < data.length; i++) {
            this.hotList.push(data[i]);
          }
          this.loading = false;
          this.form.pageNo = this.form.pageNo + 1;
          if (this.form.pageNo > res.result.pages) {
            this.noMore = true;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    keySearch(typeKey) {
      if (typeKey.code == "Enter") {
        this.onSearch();
      }
    },
    async onSearch() {
      homeSeatchText(this.search);
      // 搜索埋点
      if (this.$analytics) {
        this.$analytics.logEvent('searchGoods');
      }

      // 搜索商品
      if (!this.search) {
        this.$Message.error(this.$t("home.searchKeywords"));
        return false;
      }

      pointUser('actions', '2001');

      //搜索链接（1688、淘宝、微店）
      if (this.search.indexOf("http://") != -1 || this.search.indexOf("https://") != -1) {
        if (this.firstPageSwitchMap && this.firstPageSwitchMap.first_page_switch_customize_order == 'ENABLE' && await searchSepUrl(this.search)) {
          let searchName = await searchSepUrl(this.search);
          this.sepSearchInfo(searchName)
          return;
        }

        if (this.search.indexOf("100buy.cc") != -1) {
          isJumpWeb(this.search)
          return;
        }

        let { id, channel } = await searchByUrl(this.search);
        channel = toSeoFriendsChannel(channel);
        if (!id) {
          return this.$Message.error(this.$t("home.IncorrectSearchlink"));
        }
        const query = {
          id: id,
          channel: channel,
        };
        if (this.userInfo.inviteCode) {
          query.inviteCode = this.userInfo.inviteCode;
        }
        let toUrl = this.$router.resolve({
          path: `/product/${channel}/${id}`
        });
        window.open(toUrl.href, "_black");
      } else {
        this.$router.push(`/goods?text=${this.search}`);
      }
    },

    createXMLHttp(arg) {
      return new Promise((resolve, reject) => {
        arg = arg || {};
        let xmlhttp;
        if (window.XMLHttpRequest) {
          // code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp = new XMLHttpRequest();
        } else {
          // code for IE6, IE5
          // eslint-disable-next-line no-undef
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
          if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
              var result = xmlhttp.responseText;
              try {
                resolve(JSON.parse(result));
              } catch (e) {
                reject({ errorMsg: "数据格式错误" });
              }
            } else {
              console.log("error:xmlhttp.status =", xmlhttp.status);
              reject(xmlhttp);
            }
          }
        };
        xmlhttp.open(arg.method || "GET", arg.url, true);
        arg.headers = arg.headers || {};
        for (let key in arg.headers) {
          xmlhttp.setRequestHeader(key, arg.headers[key]);
        }
        xmlhttp.send(arg.data);
      });
    },
    sepSearchInfo(link) {
      sessionStorage.setItem('locSepSearch', link);
      this.$router.push("/diy-order")
    },
    onProgress(event, file, fileList) {
      console.log("上传的钩子", event, file, fileList);
    },
    handleMaxSize(file) {
      this.$Message.error(`File ${file.name} is too large, no more than 100KB.`);
    },
    onSuccess(response) {
      // 上传成功
      this.uploadLoading = false;
      this.form.selfieFileUrl = response.data.saveToFilename;
      this.$Message.success("上传成功");
    },
    onError(error, file) {
      this.uploadLoading = false;
      this.$Message.error("上传失败");
    },
    handleBeforeUpload(file) {
      // 定义你的大小限制，例如2MB
      // const maxSize = 100 * 1024; // 2MB
      //
      // // 检查文件大小
      // if (file.size > maxSize) {
      //   this.handleMaxSize(file);
      //   return false;
      // }
      this.uploadLoading = true;
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.imgUrl = reader.result; //将_base64赋值给图片的src，实现图片预览
        this.onProductUpload(reader.result);
      };
      return false; //阻止图片继续上传，使得form表单提交时统一上传
    },
    onProductUpload(base) {
      productUpload(base, this.config.defaultPlatformChannel)
        .then((res) => {
          this.uploadLoading = false;
          this.$router.push(`/goods?id=${res.result}&type=image`);
        })
        .catch(() => {
          this.uploadLoading = false;
        });
    },
  },
  beforeDestroy() {
    leaveHomePage();
  },
};
</script>

<style scoped lang="less">
@import './index.less';
</style>
